import {Table} from "antd";
import {useEffect, useMemo, useState} from "react";
import {GetState} from "@/utils/constant";

export default function useTable({
    columns,
    xhr,
    extraParams={}
                                 }){

    const [dataSource,setDataSource] = useState([]),
        [pagination,setpagination] = useState({
            current:1,
            pageSize:10
        }),
        [sort,setSort] = useState(),
        [loading,setLoading] = useState(false)

    useEffect(()=>{
        queryList().then(r => {})
    },[])
    async function queryList(params={}){
        const pagination = await GetState(setpagination)
        setLoading(true)
        return ax.get(xhr.query,{
            params:{
                ...extraParams,
                current:pagination.current,
                pageSize:pagination.pageSize,
                ...params
            }
        }).then(res=>{
            setpagination({
                current: res.current,
                pageSize: res.pageSize,
                total:res.total
            })
            setDataSource(res.data)
        }).finally(()=>{
            setLoading(false)
        })
    }
    function onTableChange(pagination,sorter){
        setpagination(pagination)
        setSort(sorter)
        queryList().then(r=>{})
    }
    return {
        queryList,
        tableDOM:<Table
            rowKey={"ID"}
            columns={columns.map(item=>{
                if (item.render === undefined){
                    item.render=function (text){
                        return text || "-"
                    }
                }
                return item;
            })}
            loading={loading}
            dataSource={dataSource}
            pagination={pagination}
            onChange={onTableChange}
        />
    }
}